package com.gao.mybatis.parse;

import com.gao.mybatis.configuration.Configuration;
import com.gao.mybatis.configuration.MappedStatement;
import com.gao.mybatis.configuration.SqlCommandType;
import org.dom4j.Element;

import java.util.List;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 * @since 2020-03-28 22:04
 */
public class MapperXmlParser extends XmlParser {

    public MapperXmlParser(Configuration configuration) {
        super(configuration);
    }

    @Override
    Configuration doParse(Element rootElement,Configuration configuration) throws Exception {
        String namespace = rootElement.attributeValue("namespace");
        List<Element> elements = rootElement.elements();
        for (Element ele : elements) {
            MappedStatement statement = new MappedStatement();
            statement.setId(namespace+"."+ele.attributeValue("id"));
            statement.setParameterType(ele.attributeValue("parameterType"));
            statement.setResultType(ele.attributeValue("resultType"));
            statement.setSql(ele.getTextTrim());
            String name = ele.getName();
            if("select".equals(name)){
                statement.setSqlCommandType(SqlCommandType.SELECT);
            }
            else if("update".equals(name)){
                statement.setSqlCommandType(SqlCommandType.UPDATE);
            }
            else if("delete".equals(name)){
                statement.setSqlCommandType(SqlCommandType.DELETE);
            }
            else if("insert".equals(name)){
                statement.setSqlCommandType(SqlCommandType.INSERT);
            }
            else {
                statement.setSqlCommandType(SqlCommandType.UNKNOWN);
            }
            configuration.put(statement.getId(),statement);
        }
        return configuration;
    }


}
